<template>
  <el-dialog class="pageIndexCarouselDialogWrapper" :title="dialogTitle"
             :visible.sync="dialogVisible" width="60%"
             :append-to-body="true" @open="beforeOpen" @close="beforeClose" @closed="afterClose">
    <file-collection-select-dialog v-model="fileCollectionVisible" :title="selectorParams.selectorTitle"
            :multiple="selectorParams.selectorMultiple" :name="selectorParams.selectorName"
            @fileChange="imageSelectorChange"/>
    <goods-search v-model="goodSearchVisible" @change="handleGoodChange"/>
    <el-card class="carousel" shadow="hover">
      <div class="out">
        <div class="inner">
          <index-carousel-item :data="trueItem" :direction="trueItem.direction" :back-image="trueItem.backImage"
                               :title="trueItem.title" :image="trueItem.image" :link-good-id="trueItem.linkGoodId"
                               :link-good="trueItem.linkGood" :goods="trueItem.goods" :good-flag="false"/>
        </div>
      </div>
    </el-card>
    <xum-title title="参数" :title-span="24" style="margin-top: 20px;"/>
    <el-form ref="form" size="small" :model="item" :rules="ruler" :disabled="loading" label-width="80px">
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item label="编号" prop="id">
            <el-input type="text" v-model="item.id" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="背景图片" prop="backImage">
            <el-input type="text" v-model="item.backImage" :readonly="true">
              <el-button type="text" slot="suffix" icon="el-icon-search" @click="handleSelectBackImage"/>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品图片" prop="image">
            <el-input type="text" v-model="item.image" :readonly="true">
              <el-button type="text" slot="suffix" icon="el-icon-search" @click="handleSelectImage"/>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item label="标题" prop="title">
            <el-input type="text" v-model="item.title"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="链接商品" prop="linkGoodId">
            <el-input type="text" v-model="item.linkGood['name']" placeholder="点击搜索查询商品" :readonly="true">
              <el-button type="text" icon="el-icon-search"  slot="suffix"
                         @click="openGoodSearchDialog('linkGood')"/>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="顺序号" prop="sequence">
            <el-input-number v-model="item.sequence"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item label="次商品1" prop="subGoodId1">
            <el-input type="text" v-model="item.subGood1['name']" placeholder="点击搜索查询商品" :readonly="true">
              <el-button type="text" icon="el-icon-search"  slot="suffix"
                         @click="openGoodSearchDialog('subGood1')"/>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="次商品2" prop="subGoodId2">
            <el-input type="text" v-model="item.subGood2['name']" placeholder="点击搜索查询商品" :readonly="true">
              <el-button type="text" icon="el-icon-search"  slot="suffix"
                         @click="openGoodSearchDialog('subGood2')"/>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="次商品3" prop="subGoodId3">
            <el-input type="text" v-model="item.subGood3['name']" placeholder="点击搜索查询商品" :readonly="true">
              <el-button type="text" icon="el-icon-search"  slot="suffix"
                         @click="openGoodSearchDialog('subGood3')"/>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="16">
        <el-col :span="8">
          <el-form-item label="方向" prop="direction">
            <el-select v-model="item.direction" placeholder="选择方向" @change="handleDirectionChange">
              <el-option v-for="item in optionsList" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button @click="closeDialog" size="small">关闭</el-button>
      <el-button @click="reset" size="small" :disabled="loading">重置</el-button>
      <el-button @click="handleSubmit" type="primary" :loading="loading" size="small">{{submitText}}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import IndexCarouselItem from '@pages/page/part/pageIndexCarousel/IndexCarouselItem'
import XumTitle from '@/components/XumTitle'
import FileCollectionSelectDialog from '@/components/upload/FileCollectionSelectDialog'
import PageIndexCarouselInsertDTO, {
  PageIndexCarouselDirection,
  PageIndexCarouselType
} from '@/api/entity/PageIndexCarouselInsertDTO'
import GoodsSearch from '@pages/goods/part/GoodsSearch'
import { changeIndexCarousel, insertIndexCarousel } from '@/api/ApiPageIndex'
import { ResultCode } from '@/constants/constants'
import { eq } from '@/utils/Utils'
import PageIndexCarouselChangeDTO from '@/api/entity/PageIndexCarouselChangeDTO'
export default {
  name: 'PageIndexCarouselDialog',
  components: { GoodsSearch, FileCollectionSelectDialog, XumTitle, IndexCarouselItem },
  props: {
    visible: {
      required: false,
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      required: false,
      default: 'add'
    },
    data: {
      type: Object,
      required: false,
      default: null
    }
  },
  model: {
    event: 'visible',
    prop: 'visible'
  },
  data () {
    return {
      submitLoading: false,
      dialogVisible: false,
      fileCollectionVisible: false,
      goodSearchVisible: false,
      goodSearchType: '',
      optionsList: [{
        value: PageIndexCarouselDirection.DIRECTION_LEFT,
        label: PageIndexCarouselDirection.DIRECTION_LEFT
      }, {
        value: PageIndexCarouselDirection.DIRECTION_RIGHT,
        label: PageIndexCarouselDirection.DIRECTION_RIGHT
      }],
      selectorParams: {
        type: 'backImage',
        selectorTitle: '选择背景图片',
        selectorMultiple: false,
        selectorName: 'carouselBackgroundImage'
      },
      item: {
        id: '',
        direction: 'LEFT',
        backImage: '',
        backImageFileId: '',
        image: '',
        imageFileId: '',
        title: '',
        linkGoodId: '',
        sequence: 0,
        linkGood: {
          id: '',
          name: ''
        },
        subGoodId1: '',
        subGoodId2: '',
        subGoodId3: '',
        subGood1: {
          id: '',
          name: ''
        },
        subGood2: {
          id: '',
          name: ''
        },
        subGood3: {
          id: '',
          name: ''
        }
      },
      ruler: {
        backImage: [{
          required: true,
          message: '背景图片不能为空',
          trigger: ['blur', 'change']
        }],
        image: [{
          required: true,
          message: '商品图片不能为空',
          trigger: ['blur', 'change']
        }],
        direction: [{
          required: true,
          message: '图片方向不能为空',
          trigger: ['blur', 'change']
        }],
        title: [{
          required: true,
          message: '标题不能为空',
          trigger: ['blur', 'change']
        }],
        sequence: [{
          required: true,
          message: '顺序号不能为空',
          trigger: ['blur', 'change']
        }],
        linkGoodId: [{
          required: true,
          message: '链接商品不能为空',
          trigger: ['blur', 'change']
        }]
      },
      tempItem: {}
    }
  },
  computed: {
    loading () {
      return this.submitLoading
    },
    trueItem () {
      const item = Object.assign({}, this.item)
      const goods = []
      if (this.item.subGoodId1 && this.item.subGood1) {
        goods.push(this.item.subGood1)
      }
      if (this.item.subGoodId2 && this.item.subGood2) {
        goods.push(this.item.subGood2)
      }
      if (this.item.subGoodId3 && this.item.subGood3) {
        goods.push(this.item.subGood3)
      }
      item.goods = goods
      return item
    },
    subGoodIdList () {
      const list = []
      if (this.item.subGoodId1 && this.item.subGood1) {
        list.push(this.item.subGoodId1)
      }
      if (this.item.subGoodId2 && this.item.subGood2) {
        list.push(this.item.subGoodId2)
      }
      if (this.item.subGoodId3 && this.item.subGood3) {
        list.push(this.item.subGoodId3)
      }
      return list
    },
    isEdit () {
      return this.type === 'edit' && this.data && this.data.id && this.data.id > 0
    },
    isAdd () {
      return !this.isEdit
    },
    dialogTitle () {
      return this.isEdit ? '编辑数据' : '添加轮播图'
    },
    submitText () {
      return this.isEdit ? '提交修改' : '添加数据'
    }
  },
  methods: {
    initAdd () {
      this.item = {
        id: '',
        direction: 'LEFT',
        backImage: '',
        backImageFileId: '',
        image: '',
        imageFileId: '',
        title: '',
        linkGoodId: '',
        sequence: 0,
        linkGood: {
          id: '',
          name: ''
        },
        subGoodId1: '',
        subGoodId2: '',
        subGoodId3: '',
        subGood1: {
          id: '',
          name: ''
        },
        subGood2: {
          id: '',
          name: ''
        },
        subGood3: {
          id: '',
          name: ''
        }
      }
      this.tempItem = Object.assign({}, this.item)
    },
    initEdit (data) {
      const temp = Object.assign({
        subGoodId1: '',
        subGoodId2: '',
        subGoodId3: '',
        subGood1: {
          id: '',
          name: ''
        },
        subGood2: {
          id: '',
          name: ''
        },
        subGood3: {
          id: '',
          name: ''
        }
      }, data)
      const goods = temp['goods']
      if (goods && typeof goods === 'object') {
        const size = goods.length
        let good
        if (size > 0) {
          good = goods[0]
          if (good && good.id) {
            temp.subGoodId1 = good.id
            temp.subGood1 = good
          }
        }
        if (size > 1) {
          good = goods[1]
          if (good && good.id) {
            temp.subGoodId2 = good.id
            temp.subGood2 = good
          }
        }
        if (size > 2) {
          good = goods[2]
          if (good && good.id) {
            temp.subGoodId3 = good.id
            temp.subGood3 = good
          }
        }
      }
      this.item = temp
      this.tempItem = Object.assign({}, this.item)
    },
    /**
     * 初始化数据
     */
    initData () {
      if (this.isAdd) {
        this.initAdd()
      } else {
        this.initEdit(this.data)
      }
      if (this.$refs['form']) {
        this.$refs['form'].resetFields()
      }
      this.fileCollectionVisible = false
      this.goodSearchVisible = false
    },
    /**
     * 对话框打开前初始化数据
     */
    beforeOpen () {
      this.initData()
    },
    /**
     * 对话框关闭前关闭子对话框
     */
    beforeClose () {
      this.fileCollectionVisible = false
      this.goodSearchVisible = false
    },
    /**
     * 对话框关闭后也初始化数据
     */
    afterClose () {
      this.initData()
    },
    /**
     * 对话框关闭按钮关闭对话框
     */
    closeDialog () {
      this.dialogVisible = false
    },
    /**
     * 重置按钮重置对话框数据
     */
    reset () {
      this.initData()
    },
    handleAdd () {
      this.submitLoading = true
      const params = PageIndexCarouselInsertDTO.instance()
      params.setType(PageIndexCarouselType.TYPE_DEFAULT)
      params.setDirection(this.item.direction)
      params.setBackImage(this.item.backImage)
      params.setBackImageFileId(this.item.backImageFileId)
      params.setImage(this.item.image)
      params.setImageFileId(this.item.imageFileId)
      params.setSequence(0)
      params.setTitle(this.item.title)
      params.setSequence(this.item.sequence)
      params.setLinkGoodId(this.item.linkGoodId)
      params.setGoodIdList(this.subGoodIdList)
      insertIndexCarousel(params, data => {
        if (data && data.code === ResultCode.OK) {
          this.$message.success('添加数据成功')
          this.$emit('change')
          this.dialogVisible = false
        }
      }, () => {
        this.submitLoading = false
      })
    },
    handleEdit () {
      if (!this.item || !this.item.id) {
        this.$message.error('数据错误')
        return
      }
      this.submitLoading = true
      const params = PageIndexCarouselChangeDTO.instance()
      params.setId(this.item.id)
      params.setType(PageIndexCarouselType.TYPE_DEFAULT)
      params.setDirection(this.item.direction)
      params.setBackImage(this.item.backImage)
      params.setBackImageFileId(this.item.backImageFileId)
      params.setImage(this.item.image)
      params.setImageFileId(this.item.imageFileId)
      params.setSequence(0)
      params.setTitle(this.item.title)
      params.setSequence(this.item.sequence)
      params.setLinkGoodId(this.item.linkGoodId)
      params.setGoodIdList(this.subGoodIdList)
      changeIndexCarousel(params, data => {
        if (data && data.code === ResultCode.OK) {
          this.$message.success('修改数据成功')
          this.$emit('change')
          this.dialogVisible = false
        }
      }, () => {
        this.submitLoading = false
      })
    },
    itemEq () {
      if (this.item && this.tempItem) {
        return this.item.imageFileId === this.tempItem.imageFileId &&
          this.item.image === this.tempItem.image &&
          this.item.backImage === this.tempItem.backImage &&
          this.item.backImageFileId === this.tempItem.backImageFileId &&
          this.item.title === this.tempItem.title &&
          this.item.linkGoodId === this.tempItem.linkGoodId &&
          this.item.sequence === this.tempItem.sequence &&
          this.item.subGoodId1 === this.tempItem.subGoodId1 &&
          this.item.subGoodId2 === this.tempItem.subGoodId2 &&
          this.item.subGoodId3 === this.tempItem.subGoodId3 &&
          this.item.direction === this.tempItem.direction
      } else {
        return eq(this.item, this.tempItem)
      }
    },
    /**
     * 提交数据
     */
    handleSubmit () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.isAdd) {
            this.handleAdd()
          } else {
            if (!this.itemEq()) {
              this.handleEdit()
            } else {
              this.$message.info('数据未修改')
            }
          }
        }
      })
    },
    /**
     * 选择背景图片
     */
    handleSelectBackImage () {
      this.selectorParams.type = 'backImage'
      this.selectorParams.selectorTitle = '选择背景图片'
      this.selectorParams.selectorName = 'carouselBackgroundImage'
      this.selectorParams.selectorMultiple = false
      this.fileCollectionVisible = true
    },
    /**
     * 选择商品图片
     */
    handleSelectImage () {
      this.selectorParams.type = 'goodImage'
      this.selectorParams.selectorTitle = '选择商品图片'
      this.selectorParams.selectorName = 'carouselImage'
      this.selectorParams.selectorMultiple = false
      this.fileCollectionVisible = true
    },
    /**
     * 选择图片发生改变
     */
    imageSelectorChange (list) {
      if (list && typeof list === 'object' && list.length > 0) {
        if (this.selectorParams.type === 'backImage') {
          const item = list[0]
          if (item) {
            this.item.backImage = item.url
            this.item.backImageFileId = item.fileId
          }
        }
        if (this.selectorParams.type === 'goodImage') {
          const item = list[0]
          if (item) {
            this.item.image = item.url
            this.item.imageFileId = item.fileId
          }
        }
      }
    },
    /**
     * 方向改变
     */
    handleDirectionChange (val) {
      if (val && this.item) {
        this.item.direction = val
      }
    },
    /**
     * 打开商品搜索对话框
     * @param {String} val 搜索类型
     */
    openGoodSearchDialog (val) {
      if (val) {
        this.goodSearchType = val
        this.goodSearchVisible = true
      } else {
        this.$message.error('错误的搜索类型')
      }
    },
    /**
     * 转换商品数据
     */
    convertGoodData (item) {
      // 获取price
      item.price = -1
      if (item && item['subGoodList'] && typeof item['subGoodList'] === 'object' &&
        item['subGoodList'].length > 0) {
        const items = item['subGoodList']
        items.forEach(i => {
          if (i && (item.price === -1 || (i.price && i.price < item.price))) {
            item.price = i.price
          }
        })
      }
      // 获取image
      if (item && item['goodPictureList'] && item['goodPictureList'].length > 0) {
        const imageItem = item['goodPictureList'][0]
        item.image = imageItem.image
        item.imageFileId = imageItem.imageFileId
      }
      return item
    },
    /**
     * 选择商品改变
     */
    handleGoodChange (val) {
      if (val && val.id) {
        if (this.goodSearchType === 'linkGood') {
          this.item.linkGoodId = val.id
          this.item.linkGood = this.convertGoodData(val)
        } else if (this.goodSearchType === 'subGood1') {
          this.item.subGoodId1 = val.id
          this.item.subGood1 = this.convertGoodData(val)
        } else if (this.goodSearchType === 'subGood2') {
          this.item.subGoodId2 = val.id
          this.item.subGood2 = this.convertGoodData(val)
        } else if (this.goodSearchType === 'subGood3') {
          this.item.subGoodId3 = val.id
          this.item.subGood3 = this.convertGoodData(val)
        }
      }
    }
  },
  watch: {
    visible (val) {
      this.dialogVisible = val
    },
    dialogVisible (val) {
      this.$emit('visible', val)
    },
    type () {
      this.initData()
    }
  }
}
</script>

<style scoped lang="scss">
  .pageIndexCarouselDialogWrapper{
    .carousel{
      margin-top: -10px;
      width: 70%;
      margin-left: 15%;
      .out{
        width: 100%;
        height: 330px;
        position: relative;
        cursor: pointer;

        .inner{
          width: 200%;
          height: 200%;
          transform: scale(0.5, 0.5);
          position: absolute;
          left: -50%;
          top: -50%;
        }

      }
    }
  }
</style>
